package com.wangjw.netty.designPatten;

import java.util.ArrayList;
import java.util.List;

/**
 * @see io.netty.channel.ChannelFuture
 *
 * Created by wangjw on 18/7/5.
 */
public class ObserverDemo {

    /**
     * 被观察者
     */
    public interface Observerable {

        void registerObserver(Observer observer);

        void removeObserver(Observer observer);

        void notifyObserver();
    }

    /**
     * 观察者
     */
    public interface Observer {
        void notify(String message);
    }

    /**
     * 女神
     */
    public static class Girl implements Observerable {

        private String message;

        List<Observer> observerList;

        public Girl() {
            observerList = new ArrayList<>();
        }

        @Override
        public void registerObserver(Observer observer) {
            observerList.add(observer);
        }

        @Override
        public void removeObserver(Observer observer) {
            observerList.remove(observer);
        }

        @Override
        public void notifyObserver() {
            for (Observer observer : observerList) {
                observer.notify(message);
            }
        }

        public void hasBoyFirend() {
            message = "女神有男朋友了";
            notifyObserver();
        }

        public void getMarried() {
            message = "女神结婚了，你们都死心吧！";
            notifyObserver();
        }

        public void getSingled() {
            message = "女神单身了，你们有机会了";
            notifyObserver();
        }
    }

    /**
     * 男孩
     */
    public static class Boy implements Observer {

        @Override
        public void notify(String message) {
            System.out.println("男孩收到消息：" + message);
        }
    }

    /**
     * 男人
     */
    public static class Man implements Observer {

        @Override
        public void notify(String message) {
            System.out.println("男人收到消息：" + message);
        }
    }

    /**
     * 老男人
     */
    public static class OldMan implements Observer {

        @Override
        public void notify(String message) {
            System.out.println("老男人收到消息：" + message);
        }
    }

    public static void main(String[] args) {
        Girl girl = new Girl();

        Boy boy = new Boy();
        Man man = new Man();
        OldMan oldMan = new OldMan();

        girl.registerObserver(boy);
        girl.registerObserver(man);
        girl.registerObserver(oldMan);

        girl.hasBoyFirend();
        System.out.println("========");

        girl.removeObserver(oldMan);
        girl.getMarried();
        System.out.println("========");

        girl.registerObserver(oldMan);
        girl.getSingled();
        System.out.println("========");
    }
}
